﻿using System.IO;

namespace SecurePad
{
    public class SecurePadFile
    {
        public string FilePath { get; private set; }

        public string Content { get; private set; }

        public bool IsEncrypted { get; private set; }

        public bool OpenFile(string filePath)
        {
            this.Content = File.ReadAllText(filePath);
            this.IsEncrypted = false;
            this.FilePath = filePath;
            return true;
        }

        public bool OpenFile(string filePath, string password)
        {
            Encrypter encrypter = new Encrypter();
            encrypter.Key = password;
            string text = encrypter.Decrypt(File.ReadAllText(filePath));
            if (text == null)
            {
                this.Content = null;
                this.FilePath = null;
                this.IsEncrypted = false;
                return false;
            }

            this.Content = text;
            this.FilePath = filePath;
            this.IsEncrypted = true;
            return true;
        }

        public void Save(string filePath, string content)
        {
            this.Content = content;
            this.IsEncrypted = false;
            this.FilePath = filePath;
            File.WriteAllText(filePath, content);
        }

        public void Save( string filePath, string content, string password)
        {
            this.Content = content;
            this.FilePath = filePath;
            this.IsEncrypted = true;

            if (File.Exists(filePath) == false)
            {
                File.Create(filePath).Dispose();
            }

            Encrypter encrypter = new Encrypter();
            encrypter.Key = password;
            File.WriteAllText(filePath, encrypter.Encrypt(content));
        }
    }
}
